using UnityEngine;
using System.Collections;

[System.Serializable]
public class SpawnOnTrigger : MonoBehaviour {
	
	public UnityEngine.SkinnedMeshRenderer objectToSpawn;
	public bool despawnOnExit = false;
	public bool triggerOnce = true;
	public float secondsToDespawn = 0.3f;
	
	private bool triggered = false;
	private bool exited = false;
	private float time = -1f;

	// Use this for initialization
	void Start () {
		if (Application.isPlaying)
			objectToSpawn.renderer.enabled = false;
	}
	
	// Update is called once per frame
	void Update () {
		if (triggered) {
			float currentTime = Time.time;
			if (currentTime-time >= secondsToDespawn) {
				objectToSpawn.renderer.enabled = false;
			}
		}
	}
	
	void OnTriggerEnter()  {
		if (!triggered) {
			objectToSpawn.renderer.enabled = true;
			if (triggerOnce)
				triggered = true;
			
			time = Time.time;
		}
	}
	
	void OnTriggerExit() {
		if (triggered && !exited) {
			if (despawnOnExit)
				objectToSpawn.renderer.enabled = false;
			
			if (triggerOnce)
				exited = true;
		}
	}
}
